<template>
  <div class="ai-suggestion-card">
    <div class="card-header">
      <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2.69l5.66 5.66a8 8 0 1 1-11.31 0z"></path></svg>
      <h4>AI 智能排班建议</h4>
    </div>
    <div class="card-body">
      <p>根据当前警力状况和历史警情数据，系统建议对排班进行以下优化：</p>
      <ol v-if="parsedSuggestions.length > 0">
        <li v-for="(suggestion, index) in parsedSuggestions" :key="index">{{ suggestion }}</li>
      </ol>
      <div v-else class="no-suggestions">
        <p class="text-muted">暂无有效的排班建议</p>
      </div>
    </div>
    <div class="card-footer">
      <button class="btn btn-primary" @click="applySuggestions" :disabled="parsedSuggestions.length === 0">
        应用AI建议
      </button>
    </div>

    <SchedulingFormModal
      v-if="isSchedulingFormOpen"
      :isEditMode="false"
      :initialData="currentSuggestionData"
      :policeList="[]"
      @close="handleFormClose"
      @save="handleFormSave"
    />
  </div>
</template>

<script setup lang="ts">
import { defineProps, ref, computed } from 'vue';
import api from '@/utils/axios';
import SchedulingFormModal from './SchedulingFormModal.vue';

const API_BASE_URL = 'http://localhost:8080/api/auth';

const props = defineProps({
  suggestions: {
    type: [String, Array],
    default: () => []
  }
});

const parsedSuggestions = computed(() => {
  if (!props.suggestions || (Array.isArray(props.suggestions) && props.suggestions.length === 0)) return [];

  if (Array.isArray(props.suggestions)) {
    return props.suggestions.map((s, i) => `建议 ${i+1}: ${s}`);
  }

  try {
    // 不再检查 "AI建议排班信息: " 前缀，直接按分号分割
    const content = props.suggestions.split('; ').filter(Boolean);
    return content.map((s, i) => `建议 ${i+1}: ${s}`);
  } catch (error) {
    console.error('解析AI建议出错:', error);
    return [props.suggestions || '无法解析的AI建议'];
  }
});

const isSchedulingFormOpen = ref(false);
const currentSuggestionIndex = ref(0);
const currentSuggestionData = ref(null);

// 核心改进：兼容多种格式的解析逻辑
const parseSuggestionToFormData = (suggestion: string) => {
  console.log('尝试解析建议:', suggestion);

  // 模式1: 包含 "建议 X: " 前缀的格式
  const pattern1 = /建议 \d+: (\S+) \[(\d{4}-\d{2}-\d{2})\] \[(\d{2}:\d{2})-(\d{2}:\d{2})\] \[([^\]]+)\] \[([^\]]+)\] \[([^\]]+)\]/;
  let match = suggestion.match(pattern1);

  if (match) {
    const [, shiftName, date, startTime, endTime, officersStr, location, taskDescription] = match;
    return formatData(shiftName, date, startTime, endTime, officersStr, location, taskDescription);
  }

  // 模式2: 不包含 "建议 X: " 前缀的纯格式
  const pattern2 = /\[(\S+)\] \[(\d{4}-\d{2}-\d{2})\] \[(\d{2}:\d{2})-(\d{2}:\d{2})\] \[([^\]]+)\] \[([^\]]+)\] \[([^\]]+)\]/;
  match = suggestion.match(pattern2);

  if (match) {
    const [, shiftName, date, startTime, endTime, officersStr, location, taskDescription] = match;
    return formatData(shiftName, date, startTime, endTime, officersStr, location, taskDescription);
  }

  console.error('无法解析的建议格式:', suggestion);
  return null;
};

// 数据格式化函数
const formatData = (
  shiftName: string,
  date: string,
  startTime: string,
  endTime: string,
  officersStr: string,
  location: string,
  taskDescription: string
) => {
  // 解析人员列表 [龙懿轩, 谢天宇, 石熠彤]
  const officers = officersStr
    .split(',')
    .map(name => name.trim()) // 去除前后空格
    .filter(Boolean) // 过滤空值
    .map(name => ({ officerName: name }));

  return {
    shiftName,
    date,
    startTime,
    endTime,
    officers: officers.length > 0 ? officers : [{ officerName: '未指定' }],
    location,
    taskDescription
  };
};

const applySuggestions = () => {
  if (parsedSuggestions.value.length === 0) return;

  currentSuggestionIndex.value = 0;
  const suggestion = parsedSuggestions.value[currentSuggestionIndex.value];
  currentSuggestionData.value = parseSuggestionToFormData(suggestion);

  console.log('传递给表单的初始数据:', currentSuggestionData.value);
  isSchedulingFormOpen.value = true;
};

const handleFormClose = () => {
  currentSuggestionIndex.value++;
  if (currentSuggestionIndex.value < parsedSuggestions.value.length) {
    const suggestion = parsedSuggestions.value[currentSuggestionIndex.value];
    currentSuggestionData.value = parseSuggestionToFormData(suggestion);
    isSchedulingFormOpen.value = true;
  } else {
    isSchedulingFormOpen.value = false;
  }
};

const handleFormSave = async (data: any) => {
  data.timeRange = `${data.startTime}-${data.endTime}`;
  try {
    await api.post(`${API_BASE_URL}/shifts`, data);
    alert('排班信息保存成功！');
    handleFormClose();
  } catch (error) {
    console.error('保存失败:', error);
    alert('保存排班信息出错，请稍后重试！');
  }
};
</script>

<style scoped>
@import "@/assets/styles/views/admin/AiSuggestionCard.css";
.no-suggestions {
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
  color: #6c757d;
}
</style>
